package com.logistics.admin;

import java.io.File;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import cn.easybuild.core.exceptions.SystemException;
import cn.easybuild.core.security.user.User;
import cn.easybuild.core.web.struts2.JsonBasedStruts2Action;
import cn.easybuild.pojo.Paging;

import com.logistics.AdminUser;
import com.logistics.SystemConfig;

public class BaseAction extends JsonBasedStruts2Action {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public static final String LIST = "list";
	
	public static final String SLASH = "/";
	
	/**
	 * 编辑器图片上传文件夹
	 */
	public static final String UEDITOR_FOLDER = "ueditor";
	
	/**
	 * session保存管理员登陆信息对应的key
	 */
	private static final String ADMIN_LOGON_KEY = "admin_logon";
	
	public BaseAction(boolean requirelLogin) {
		super(requirelLogin);
	}
	
	public BaseAction() {
		super(true);
	}
	
	private SystemConfig config;
	
	public SystemConfig getConfig() {
		return config;
	}

	@Autowired
	public void setConfig(SystemConfig config) {
		this.config = config;
	}

	/**
	 * 用来判断管理员是否登陆
	 * 
	 * @return
	 */
	@Override
	public boolean isLogon() {
		if (isRequireLogon()) {
			return getLogonUser() != null;
		}
		return super.isLogon();
	}
	
	@Override
	public User getLogonUser() {
		return (User)getSession().getAttribute(ADMIN_LOGON_KEY);
	}
	
	protected void setLogonUser(AdminUser user) {
		getSession().setAttribute(ADMIN_LOGON_KEY, user);
	}
	
	protected void removeLogonUser(){
		getSession().removeAttribute(ADMIN_LOGON_KEY);
	}
	
	public AdminUser getLogonAdminUser() {
		return (AdminUser) getLogonUser();
	}
	
	private String id;
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public boolean isAddOperation(){
		return (StringUtils.isBlank(getId()));
	}
	
	/**
	 * 上传图片
	 * @param image
	 * @param filename
	 * @return String
	 */
	protected String saveImageFile(File image, String filename, String uploadFolder) {
			
		if (image == null || !image.exists()) {
			return "";
		}
		String ext = "." + FilenameUtils.getExtension(filename);
		String newFileName = System.currentTimeMillis() + ext;
		
		File iconUploadFolder = new File(uploadFolder);
		
		File iconFile = new File(iconUploadFolder, newFileName);
		try {
			FileUtils.copyFile(image, iconFile);
		} catch (Exception e) {
			throw new SystemException(e);
		}finally {
			image.delete();
		}
		
		return newFileName;
	}
	
	/**
	 * 删除文件
	 *
	 * @param filename
	 */
	protected void deleteFile(String filename, String uploadFolder) {
		
		if (StringUtils.isEmpty(filename)) {
			return;
		}
		
		File imageUploadFolder = new File(uploadFolder);
		
		File file = new File(imageUploadFolder, filename);
		if (file.exists()) {
			file.delete();
		}
	}
	/**
	 * 根据传入的文件名称获取文件夹的绝对路径
	 *
	 * @param folder
	 * @return systempConfig.ImageUploadFolder + folder
	 */
	public String getImageUploadFolder(String folder) {
		File file = new File(getConfig().getImageUploadFolder(), folder);
		if (!file.exists()) {
			file.mkdirs();
		}
		return file.getAbsolutePath();
	}
	
	/**
	 * 根据传入folder、name 获得访问路径
	 *
	 * @param folder
	 * @param name
	 * @return
	 */
	public String getImageURl(String folder, String name) {
		
		if (StringUtils.isEmpty(folder) || StringUtils.isEmpty(name)) {
			return null;
		}
		
		return getConfig().getImageHost() + SLASH + folder + SLASH + name; 
	}
	
	/**
	 * 编辑器图片上传文件路径
	 *
	 * @return
	 */
	public String getUeditorImageUploadFolder() {
		return getConfig().getImageUploadFolder() + IOUtils.DIR_SEPARATOR + UEDITOR_FOLDER;
	}
	
	/**
	 * 编辑器图片上传文件
	 *
	 * @return
	 */
	public String getUeditorImageHost() {
		return getConfig().getImageHost() + "/" + UEDITOR_FOLDER;
	}
	
	/**
	 * 
	 *
	 * @param str
	 */
	public void outputString(String json) {
		HttpServletResponse response = getResponse();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.print(json);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (writer != null) {
				writer.close();
				writer = null;
			}
		}
	}
	
	/**
	 * 获取网站地址
	 *
	 * @return
	 */
	public String getWebPath() {
		HttpServletRequest request = getRequest();
		
		String temp = request.getScheme() + "://" + request.getServerName();
		int port = request.getServerPort();
		
		if( port != 80) {
			temp += ":" + port;
		}
		
		temp += request.getContextPath();
		
		return temp;
	}
	
	private static final int MAX_DISPLAY_PAGE_ITEMS = 10;
	
	private int[] displayPages;

	public int[] getDisplayPages() {
		
		Paging paging = getPaging();
		
		if (paging == null) {
			return new int[]{};
		}
		
		if (displayPages != null) {
			return displayPages;
		}
		
		int start = (paging.getCurrentPage()-1) / MAX_DISPLAY_PAGE_ITEMS * MAX_DISPLAY_PAGE_ITEMS;
		int end = Math.min(paging.getPages(), start + MAX_DISPLAY_PAGE_ITEMS);
		
		displayPages = new int[end - start];
		
		int index = 0;
		for (int i=start; i<end; i++) {
			displayPages[index++] = i+1;
		}
		
		return displayPages;
		
	}
}
